package search;

import treeview.NodeView;
import treeview.unit.AbstractUnitView;
import treeview.unit.ImageView;
import treeview.unit.TextView;

import java.util.ArrayList;

/**
 * Created by Pavel Nikolaev
 */
public class LeafIndexer extends LeafVisitor {
    private ArrayList<AbstractUnitView> myLeafViews;
    private int myCurrentOffset;

    public LeafIndexer(NodeView root) {
        myLeafViews = new ArrayList<AbstractUnitView>();
        myCurrentOffset = 0;
        root.accept(this);
    }

    public void update(NodeView root) {
        myLeafViews.clear();
        myCurrentOffset = 0;
        root.accept(this);
    }

    public void visitTextView(TextView view) {
        process(view);
    }

    public void visitImageView(ImageView view) {
        process(view);
    }

    public void visitUnitView(AbstractUnitView view) {
        process(view);
    }

    private void process(AbstractUnitView view) {
        myLeafViews.add(view);
        view.setIndex(myLeafViews.size() - 1);
        view.setReferenceOffset(myCurrentOffset);
        myCurrentOffset = view.getEndOffset();
    }

    public AbstractUnitView getLeafView(int index) {
        return myLeafViews.get(index);
    }

    public ArrayList<AbstractUnitView> getIndexedViews() {
        return myLeafViews;
    }
}
